package event

import debug.debug
import heap.EventNotifiable

class EventMinorGC(data: List<String>) : EventOutGC() {
    companion object {
        const val TYPE = "[GC"
        const val GC_TYPE = "MinorGC"
        private const val M = 1024
    }

    var youngBefore: Long = 0
    var youngAfter: Long = 0
    var youngCapacity: Long = 0

    var heapBefore: Long = 0
    var heapAfter: Long = 0
    var heapCapacity: Long = 0

    var time = 0.0

    init {
        val infos = data[0].split('[', ']').filter { it.isNotBlank() }
        for ((index, s) in infos.withIndex()) {
            when(index) {
                0 -> {
                    gcReason = s.substring(s.indexOfFirst { it == '(' } + 1, s.indexOfLast { it == ')' })
                    "gcReason: $gcReason".debug()
                }
                1 -> {
                    val info = s.split(' ', '(', ')').filter { it.isNotBlank() }
                    info.forEachIndexed { index, s ->
                        when(index) {
                            1 -> {
                                youngBefore = s.substringBefore('K').toLong() * M
                                youngAfter = s.substringAfter('>').substringBefore('K').toLong() * M
                                "youngBefore: $youngBefore".debug()
                                "youngAfter: $youngAfter".debug()
                            }
                            2 -> {
                                youngCapacity = s.substringBefore('K').toLong() * M
                                "youngCapacity: $youngCapacity".debug()
                            }
                        }
                    }
                }
                2 -> {
                    val info = s.split(' ', '(', ')', 'K', '-', '>', ',').filter { it.isNotBlank() }
                    heapBefore = info[0].toLong() * M
                    heapAfter = info[1].toLong() * M
                    heapCapacity = info[2].toLong() * M
                    time = info[3].toDouble()
                    "heapBefore: $heapBefore".debug()
                    "heapAfter: $heapAfter".debug()
                    "heapCapacity: $heapCapacity".debug()
                    "time: $time".debug()
                }
            }
        }
    }

    override fun toString(): String {
        return "EventMinorGC(youngBefore=$youngBefore, youngAfter=$youngAfter, youngCapacity=$youngCapacity, heapBefore=$heapBefore, heapAfter=$heapAfter, heapCapacity=$heapCapacity, time=$time, gcReason='$gcReason')"
    }

    override fun notifyTHeap(notifiable: EventNotifiable) {
        notifiable.receiveNotify(this)
    }
}